package com.adcc.ags.cgw.job;

import com.adcc.ags.cgw.configuration.UserListFactory;
import com.adcc.utility.codec.MD5;
import com.adcc.utility.log.Log;
import com.adcc.utility.xml.ADCCXML;
import com.google.common.base.Strings;
import org.quartz.*;

import javax.ws.rs.client.Client;
import javax.ws.rs.client.ClientBuilder;
import javax.ws.rs.core.Response;
import java.io.*;

/**
 * 同步用户列表作业
 */
@PersistJobDataAfterExecution
@DisallowConcurrentExecution
public class SyncGMSUserListJob implements Job{

    private static final String SYNC_USERLIST_URL = "/GWUser/syncUserList";

    /**
     * 同步用户列表
     */
    private void syncUserList(String url){
        try{
            ADCCXML adccxml = UserListFactory.getInstance().load();
            String strMD5 = (adccxml != null) ? MD5.getMD5(adccxml.createXMLString()) : "";
            String strUrl = url + "?MD5=" + strMD5;
            Client client = ClientBuilder.newClient();
            Response response = client.target(strUrl)
                    .request()
                    .get();
            if(response.getStatus() == 200){
                InputStream is  = response.readEntity(InputStream.class);
                if(is != null){
                    int intLength = -1;
                    byte[] buffer = new byte[1024];
                    StringBuffer sb = new StringBuffer();
                    while ((intLength = is.read(buffer,0,buffer.length)) > -1){
                        sb.append(new String(buffer,0,intLength));
                    }
                    if(!Strings.isNullOrEmpty(sb.toString())){
                        UserListFactory.getInstance().save(sb.toString());
                    }
                }
            }else{
                Log.error(SyncGMSUserListJob.class.getName(),"sync userlist failed status:" + response.getStatus());
            }
        }catch (Exception ex){
            Log.error(SyncGMSUserListJob.class.getName(),"syncUserList() error",ex);
        }
    }

    @Override
    public void execute(JobExecutionContext jobExecutionContext) throws JobExecutionException {
        try{
            // 同步用户配置备份文件
            SchedulerContext sc = jobExecutionContext.getScheduler().getContext();
            if(sc.containsKey(SyncGMSUserListJob.class.getSimpleName()) && !Strings.isNullOrEmpty(sc.getString(SyncGMSUserListJob.class.getSimpleName()))){
                String strUrl = sc.getString(SyncGMSUserListJob.class.getSimpleName()) + SYNC_USERLIST_URL;
                syncUserList(strUrl);
            }
        }catch (Exception ex){
            Log.error(SyncGMSUserListJob.class.getName(),"execute() error",ex);
        }
    }
}
